package com.citywithincity.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ExpandReader extends ConfigReader {

	private Map<String, String> data;
	
	@Override
	public void load(String name) throws IOException {
		Map<String, String> map = loadInputStreamMap("application.properties");
		this.data = map;
		String configName = map.get("configName");
		if(configName!=null){
			try{
				Map<String, String> newConfig = loadMap("config-"+configName+".properties");
				map.putAll(newConfig);
			}catch(IOException e){
				throw new RuntimeException("找不到配置文件"+"config-"+configName+".properties",e);
			}
		}
	}
	
	
	private static Map<String,String> loadInputStreamMap(String name) throws IOException{
		InputStream in = null;
		try {
			in = PathUtil.getInputStream(ExpandReader.class,name);
			return parseInputStream(in);
			
		} catch(IOException e){
			//	logger.warn("Config file " +name+ " not exits! ");
			return new HashMap<String, String>();
		}finally {
			IoUtil.close(in);
		}
	}
	
	private static Map<String, String> parseInputStream(InputStream in) throws IOException{
		Properties p = new Properties();
		p.load(in);
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<Object> keys = p.keys();
		while(keys.hasMoreElements()){
			String key =  (String)keys.nextElement();
			String value = p.getProperty( key);
			map.put(key, value);
		}
		return map;
	}
	
	
	private static Map<String,String> loadMap(String name) throws IOException{
		InputStream in = null;
		try {
			try{
				in = PathUtil.getConfigInputStream(ExpandReader.class,name);
			}catch(IOException e){
				logger.warn("Config file " +name+ " not exits! ");
				return new HashMap<String, String>();
			}
			return parseInputStream(in);
			
		} finally {
			IoUtil.close(in);
		}
	}

	@Override
	public String get(String key) {
		return data.get(key);
	}

	@Override
	public int getInt(String key) {
		String value = data.get(key);
		if(value==null){
			return 0;
		}
		return Integer.parseInt(value);
	}

	@Override
	public String get(String key, String defaultValue) {
		String value = data.get(key);
		if(value==null){
			return defaultValue;
		}
		return value;
	}

}
